<?php
namespace WebApper\Shortcode;

/*
 * [record_tasks id='recordTasks' ]
 *
 */
class RecordTasks extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'record_tasks';

    /**
     * Handles the [record_tasks] shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Check for required shortcode attributes
			$msg = $this->has_req_attrs( $atts );
			if ( $msg !== true )
				return $msg;
				
		// Build the shortcode output hrml string
			?>
            <div class="tab-content" id="tasks" style="display:block;">
                <div class="tab-pane active fade in" >
                    <button id="addTask" class="btn btn-primary pull-right">New task</button>
                    <table id="task_list" class="table">
                        <thead>
                            <tr>
                                <th>Subject</th>
                                <th>Description</th>
                                <th>Status</th>
                                <th>Asigned to</th>
                                <th>Due</th>
                                <th>Manage</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                            global $webapper, $wpdb;
                            $tasks = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$webapper->tables->tasks} WHERE post_id = %d", $_GET['postID'] ) );
                            $now = new \DateTime();
                            $now->setTimestamp( current_time('timestamp') );
                            foreach ( $tasks as $task ) :
                                $due = new \DateTime();
                                $due->setTimestamp( $task->due );
                                $due_in = $due->diff( $now );
                                if ( $due_in->m ) :
                                    $date_format = '%m month';
                                    $date_format .= 1 < $due_in->m ? 's' : '';
                                elseif ( $due_in->d ) :
                                    $date_format = '%d day';
                                    $date_format .= 1 < $due_in->d ? 's' : '';
                                else :
                                    $date_format = '%h hour';
                                    $date_format .= 1 < $due_in->h ? 's' : '';
                                endif;
                                
                                $user = get_user_by( 'id', $task->user_id );
                                
                                echo '<tr id="' . $task->ID . '">';
                                echo '	<td>' . $task->subject . '</td>';
                                echo '	<td>' . $task->description . '</td>';
                                echo '	<td>' . $task->status . '</td>';
                                echo '	<td id="' . $task->user_id . '">' . $user->display_name . '</td>';
                                echo '	<td>', $due_in->format( $date_format ), $due_in->invert === 0 ? ' overdue' : '', '</td>';
                                echo '	<td><a class="editTask" href="#"><i class="icon-edit"></i> Edit</a></td>';
                                echo '	<td><a class="delete_task" href="#"><i class="icon-remove"></i> delete</a></td>';
                                echo '</tr>';
                            endforeach;
                        ?>
                        </tbody>
                    </table>
                </div>
                <div class="tab-pane fade in" id="add_task">
                    <form name="addTask" id="addTask" action="" method="post" class="form-horizontal" novalidate>
                        <input type="hidden" name="action" value="web_apper<?php echo $this->shortcode; ?>" />
                        <input type="hidden" name="web_apper_nonce" value="<?php echo wp_create_nonce( 'WebApperAwesomeness!87' ); ?>" />
                        <input type="hidden" name="web_apper_task" value="add" />
                        <input type="hidden" name="web_apper_id" value="<?php echo $_GET['postID'] ?>" />
                        <input type="hidden" name="web_apper_task_id" value="" />
                        <div class="row">
                            <div class="span8">
                                
                                <div class="control-group">
                                    <label for="subject"><strong>Subject:</strong></label>
                                    <input type="text" name="subject" class="span8">
                                </div>
                                
                                <div class="control-group">
                                    <label for="description"><strong>Description:</strong></label>
                                    <!--<textarea name="description" class="span8" rows="5"></textarea>-->
                                    <?php
                                    $settings = array(
                                        'wpautop' => false,
                                        'media_buttons' => false,
                                        'textarea_name' => 'description',
                                        'textarea_rows' => 8,
                                        'tinymce' => array (
                                            'theme_advanced_buttons1' => 'formatselect,|,bold,italic,underline,|,bullist,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,spellchecker,wp_fullscreen,wp_adv'
                                        )
                                    );
                                    wp_editor( '', 'description', $settings , array( 'quicktags' => false ) );
                                    ?>
                                </div>
        
                            </div>
                            <div class="span4">

                                <div class="control-group">
                                    <label><strong>Task template:</strong></label>
                                    <select name="task_template" class="span4">
                                        <option value="custom">custom</option>
                                        <?php
                                            // Get Task template from Database
                                            global $wpdb, $webapper;
                                            $task_templates = $wpdb->get_results( "SELECT * FROM {$webapper->tables->taskTemplates}" );
                                            foreach ( $task_templates as $template ) :
                                                echo stripslashes("<option data-subject=\"$template->subject\" data-description=\"$template->description\" data-due_in=\"$template->due_in\" data-due_unit=\"$template->due_unit\" data-assign_to_user_type=\"$template->assign_to_user_type\" data-assign_to_user=\"$template->assign_to_user\" data-status=\"$template->status\">$template->name</option>");
                                            endforeach;
                                        ?>	
                                    </select>
                                </div>
                            
                                <div class="control-group">
                                    <label class="radio inline"><input type="radio" name="due" value="due_in" checked> Due in </label>
                                    <label class="radio inline"><input type="radio" name="due" value="due_on"> Due on</label>
                                </div>
                                
                                <div class="control-group" id="due_in">
                                    <label for="due_in"><strong>Due in:</strong></label>
                                    <input type="number" name="due_in" class="span1" value="1">
                                    <select name="due_in_unit" class="span2">
                                        <option value="hours">hours</option>
                                        <option value="days">days</option>
                                        <option value="weeks">weeks</option>
                                        <option value="months">months</option>
                                    </select>
                                </div>
                                
                                <div class="control-group" id="due_on" style="display:none;">
                                    <label><strong>Due on:</strong></label>
                                    <input type="date" name="due_on_date" class="span2">
                                    <select name="due_on_hour" class="span1">
                                        <option></option>
                                        <?php for ( $i = 1; $i <= 12; $i++ ) echo '<option value="' . $i . '">' . $i . '</option>'; ?>
                                    </select>
                                    <select name="due_on_ap_pm" class="span1">
                                        <option value="am">am</option>
                                        <option value="pm">pm</option>
                                    </select>
                                </div>
                                
                                <div class="control-group">
                                    <label for="assign_to_role"><strong>Assign to:</strong></label>
                                    <select name="assign_to_user" class="span2">
                                        <option value="rotate_users">rotate users</option>
                                        <?php
                                        $users = get_users( array('role' => 'staff') );
                                            foreach ( $users as $user ) :
                                                echo '<option class="role ' . $user->roles[0] . '" value="' . $user->data->ID . '">' . $user->data->display_name . '</option>';
                                            endforeach;
                                        ?>
                                    </select>
                                </div>
                                
                                <div class="control-group">
                                    <label for="status"><strong>Task status:</strong></label>
                                    <select name="status" class="span4">
                                        <option value="assigned">assigned</option>
                                        <option value="started">started</option>
                                        <option value="">complete</option>
                                    </select>
                                </div>
        
                                <div class="control-group">
                                    <input type="submit" name="submitTask" class="btn btn-primary" value="Add task" />
                                    <button id="cancelAddTask" class="btn">Cancel</button>
                                </div>
        
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <script type="text/javascript">
				jQuery(document).ready(function($) {
					$('form#addTask').bind("submit", function() {
						$('.alert').remove();  // Close any alerts that may be open
						//tinyMCE.triggerSave();
						$.ajax({
							url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
							type: "post",
							data: $("form#addTask").serialize(),
							success: function(response) {
								var result = $.parseJSON(response);  // Parse response
								if ( result.success ) {  // If ajax returns a successful save
									if ( result.task == 'add' ) {  // If we added a row
										$('table#task_list tbody').prepend('<tr><td>'+ result.taskdata.task_type +'</td><td>'+ result.taskdata.subject +'</td><td>'+ result.taskdata.description +'</td><td>'+ result.taskdata.status +'</td><td id="'+ result.taskdata.user_id +'">'+ result.taskdata.user_name +'</td><td id="'+ result.taskdata.due +'">'+ result.taskdata.due_time +'</td><td><a class="editTask" href="#"><i class="icon-edit"></i> Edit</a></td><td><a class="delete_task" href="#"><i class="icon-remove"></i> delete</a></td></tr>');
									} else if ( result.task == 'update' ) {  // If we updated a row
										$('table#task_list tbody tr#'+ result.ID).html('<td>'+ result.taskdata.task_type +'</td><td>'+ result.taskdata.subject +'</td><td>'+ result.taskdata.description +'</td><td>'+ result.taskdata.status +'</td><td id="'+ result.taskdata.user_id +'">'+ result.taskdata.user_name +'</td><td id="'+ result.taskdata.due +'">'+ result.taskdata.due_time +'</td><td><a class="edit_task" href="#"><i class="icon-edit"></i> Edit</a></td><td><a class="delete_task" href="#"><i class="icon-remove"></i> delete</a></td>');
									} else if ( result.task == 'delete' ) {  // If we deleted a row
										$('table#task_list tbody tr#'+ result.ID).remove();
									}
								}
								$('#singleRecordTabs a[href="#tasks"]').tab('show');
								$(".tab-content").prepend(result.htmlalert);  // Show and alert
							}
						});
						return false;
					});
					
					$('button#addTask').click( function() {
						$('[name="web_apper_task"]').val( 'add' );
						$('[name="web_apper_task_id"]').val('');
						$('form#addTask').resetForm();
						$('[name="submitTask"]').val( 'Add task' );
						$('#singleRecordTabs a[href="#add_task"]').tab('show');
					});
					
					$('button#cancelAddTask').click( function() {
						$('#singleRecordTabs a[href="#tasks"]').tab('show');
						return false;
					});
					
					$('a.editTask').click( function() {
						var nTr = $(this).parent().parent();
						$('[name="web_apper_task"]').val( 'update' );
						$('[name="web_apper_task_id"]').val( $(nTr).attr('id') );
						$('[name="subject"]').val( $('td:nth-child(1)', nTr).html() );
						$('[name="description"]').val( $('td:nth-child(2)', nTr).html() );
						$('[name="assign_to_user"]').val( $('td:nth-child(4)', nTr).attr('id') );
						$('[name="status"]').val( $('td:nth-child(3)', nTr).html() );
						$('[name="submitTask"]').val( 'Update task' );
						$('#singleRecordTabs a[href="#add_task"]').tab('show');
						return false;
					});
					
					$('a.delete_task').click( function() {
						var nTr = $(this).parent().parent();
						$('[name="web_apper_task"]').val( 'delete' );
						$('[name="web_apper_task_id"]').val( $(nTr).attr('id') );
						$('form#addTask').submit();
					});
					
					$('select[name="task_template"]').on('change', function() {
						$('[name="subject"]').val( $(':selected', this).data('subject') );
						$('[name="description"]').val( $(':selected', this).data('description') );
						$('[name="due"][value="due_in"]').prop('checked', true);
						$('div#due_on').fadeOut(400, function() {
							$('div#due_in').fadeIn(400);
						});
						$('[name="due_in"]').val( $(':selected', this).data('due_in') );
						$('[name="due_in_unit"]').val( $(':selected', this).data('due_unit') );
						$('[name="assign_to_role"]').val( $(':selected', this).data('assign_to_user_type') );
						$('[name="assign_to_user"]').val( $(':selected', this).data('assign_to_user') );
						$('[name="status"]').val( $(':selected', this).data('status') );
					});
					
					$('input[name="due"]').on('change', function() {
						if ( $(this).val() == 'due_in' ) {
							$('div#due_on').fadeOut(400, function() {
								$('div#due_in').fadeIn(400);
							});
						} else {
							$('div#due_in').fadeOut(400, function() {
								$('div#due_on').fadeIn(400);
							});
						}
					});
					
					$('select[name="assign_to_role"]').on('change', function() {
						if ( $(this).val() !== '' ) {
							$('[name="assign_to_user"] option.role').fadeOut(100);
							$('[name="assign_to_user"] option.' + $(this).val()).fadeIn(100);
						} else {
							$('[name="assign_to_user"] option.role').fadeIn(100);
						}
					});

				});
			</script>
 
            <?php
	}

    /**
     * Checks if current user has proper privileges
     *
	 * @param string $usercap
     * @since 1.0
     */
	static protected function user_has_cap( $usercap ) {
		if ( current_user_can( $usercap ) ) :
			return true;
		else :
			return false;
		endif;
	}

    /**
     * Handles ajax requests
     *
     * @since 1.0
     */
	function sendAjaxResponse() {
		check_ajax_referer( 'WebApperAwesomeness!87', 'web_apper_nonce' );  // Verify the security nonce
		if ( $_POST['web_apper_task'] == 'add' ) :
			echo json_encode( $this->add_record() );
		elseif ( $_POST['web_apper_task'] == 'update' ) :
			echo json_encode( $this->update_record() );
		elseif ( $_POST['web_apper_task'] == 'delete' ) :
			echo json_encode( $this->delete_record() );
		endif;
		die();  // Prevents ajax from returning a '0'
	}

    /**
     * Send response to $_POST
     *
	 * @param string $message
	 * @param string $class
	 * @param string $title
     * @since 1.0
     */
	static protected function sendResponse( $message, $class = '', $title = 'Heads Up!', $success = true, $ID = null, $taskdata = null ) {
		$htmlalert = '<div class="alert ' . $class . ' fade in"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>' . $title . '</strong> ' . $message . '</div>';
		if ( $_POST['action'] ) :  // If ajax $_POST
			$response = array(
				'success'	=> $success,
				'htmlalert' => $htmlalert,
			);
			if ( $_POST['web_apper_task'] ) :
				$response['task'] = $_POST['web_apper_task'];
			endif;
			if ( $ID !== null ) :
				$response['ID'] = $ID;
			endif;
			if ( $taskdata !== null ) :
				$response['taskdata'] = $taskdata;
			endif;
			return $response;
		else :
			echo $htmlalert;
		endif;
	}

    /**
     * Adds a new task
     *
     * @since 1.0
     */
	public function add_record() {

		if ( $_POST['due'] == 'due_in' ) :
			switch ( $_POST['due_in_unit'] ) :
				case 'hours' : $unit = 60 * 60; break;			
				case 'days' : $unit = 60 * 60 * 24; break;			
				case 'weeks' : $unit = 60 * 60 * 24 * 7; break;			
				case 'months' : $unit = 60 * 60 * 24 * 30; break;			
			endswitch;
			$due = current_time('timestamp') + ( $_POST['due_in'] * $unit );
		elseif ( $_POST['due'] == 'due_on' ) :
			$date = new \DateTime($_POST['due_on_date']);
			if ( !empty($_POST['due_on_hour']) ) :
				$_POST['due_on_ap_pm'] == 'am' ? $hours = $_POST['due_on_hour'] : $hours = $_POST['due_on_hour'] + 12;
				$date->add(new \DateInterval('PT' . $hours . 'H'));
			endif;
			$due = $date->getTimestamp();
		endif;

		if ( is_numeric( $_POST['assign_to_user'] ) ) :
			$user = $_POST['assign_to_user'];
		else :
			$user = $this->auto_assign();
		endif;

		global $webapper, $wpdb, $current_user;
		get_currentuserinfo();
		
		$task_data = array( 
			'subject' => $_POST['subject'],
			'description' => $_POST['description'],
			'task_type' => $_POST['task_type'],
			'status' => $_POST['status'],
			'due' => $due,
			'user_id' => $user,
			'author_id' => $current_user->ID,
			'post_id' => $_POST['web_apper_id'],
			'created_on' => current_time('timestamp'),
			'edited_on' => current_time('timestamp'),
		);
		
		$wpdb->insert( 
			$webapper->tables->tasks,
			$task_data,
			array( '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s', '%d', '%d', '%d' ) 
		);
		
		$record = get_post( $_POST['web_apper_id'] );
				
		$notified = web_apper_add_notification( $_POST['web_apper_id'], 'task', 'New task for' . $record->post_title, 'Long MSG', $user, current_time('timestamp') );
		
		if ( $wpdb->insert_id && $notified ) :
			$now = new \DateTime();
			$now->setTimestamp( current_time('timestamp') );
			$due = new \DateTime();
			$due->setTimestamp( $task_data['due'] );
			$due_in = $due->diff( $now );
			if ( $due_in->m ) :
				$date_format = '%m month';
				$date_format .= 1 < $due_in->m ? 's' : '';
			elseif ( $due_in->d ) :
				$date_format = '%d day';
				$date_format .= 1 < $due_in->d ? 's' : '';
			else :
				$date_format = '%h hour';
				$date_format .= 1 < $due_in->h ? 's' : '';
			endif;
			$user = get_user_by( 'id', $user );
			$task_data['user_name'] = $user->display_name;
			$task_data['due_time'] = $due_in->format( $date_format );

			return $this->sendResponse( 'Task saved.', 'alert-success', 'Hurray!', true, $wpdb->insert_id, $task_data );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem saving the task. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Updates a task
     *
     */
	public function update_record() {
		
		if ( $_POST['due'] == 'due_in' ) : // Get a due date for the task
			switch ( $_POST['due_in_unit'] ) :
				case 'hours' : $unit = 60 * 60; break;			
				case 'days' : $unit = 60 * 60 * 24; break;			
				case 'weeks' : $unit = 60 * 60 * 24 * 7; break;			
				case 'months' : $unit = 60 * 60 * 24 * 30; break;			
			endswitch;
			$due = current_time('timestamp') + ( $_POST['due_in'] * $unit );
		elseif ( $_POST['due'] == 'due_on' ) :
			$date = new \DateTime($_POST['due_on_date']);
			if ( !empty($_POST['due_on_hour']) ) :
				$_POST['due_on_ap_pm'] == 'am' ? $hours = $_POST['due_on_hour'] : $hours = $_POST['due_on_hour'] + 12;
				$date->add(new \DateInterval('PT' . $hours . 'H'));
			endif;
			$due = $date->getTimestamp();
		endif;

		if ( is_numeric( $_POST['assign_to_user'] ) ) : // Get a user to assign the task to
			$user = $_POST['assign_to_user'];
		else :
			$user = $this->auto_assign();
		endif;

		global $webapper, $wpdb, $current_user;
		get_currentuserinfo();
		
		$result = $wpdb->update( 
			$webapper->tables->tasks,
			array(
				'subject' => $_POST['subject'],
				'description' => $_POST['description'],
				'task_type' => $_POST['task_type'],
				'status' => $_POST['status'],
				'due' => $due,
				'user_id' => $user,
				'author_id' => $current_user->ID,
				'post_id' => $_POST['web_apper_id'],
				'created_on' => current_time('timestamp'),
				'edited_on' => current_time('timestamp'),
			),
			array( 'ID' => $_POST['web_apper_task_id'] ),
			array( '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s', '%d', '%d', '%d' ) 
		);
		
		$record = get_post( $_POST['web_apper_id'] );
				
		$notified = web_apper_add_notification( $_POST['web_apper_id'], 'task', 'New task for' . $record->post_title, 'Long MSG', $user, current_time('timestamp') );
				
		if ( $result === 0 ) :	
			return $this->sendResponse( 'There was a problem saving the task. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		elseif ( $result && $notified ) :	
			$now = new \DateTime();
			$now->setTimestamp( current_time('timestamp') );
			$due = new \DateTime();
			$due->setTimestamp( $task_data['due'] );
			$due_in = $due->diff( $now );
			if ( $due_in->m ) :
				$date_format = '%m month';
				$date_format .= 1 < $due_in->m ? 's' : '';
			elseif ( $due_in->d ) :
				$date_format = '%d day';
				$date_format .= 1 < $due_in->d ? 's' : '';
			else :
				$date_format = '%h hour';
				$date_format .= 1 < $due_in->h ? 's' : '';
			endif;
			$user = get_user_by( 'id', $user );
			$task_data['user_name'] = $user->display_name;
			$task_data['due_time'] = $due_in->format( $date_format );

			return $this->sendResponse( 'Task saved.', 'alert-success', 'Hurray!', true, $_POST['web_apper_task_id'], $task_data );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem saving the task. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Deletes a task
     *
     */
	public function delete_record() {
		global $webapper, $wpdb;
		$result = $wpdb->query( $wpdb->prepare( "DELETE FROM {$webapper->tables->tasks} WHERE id = %d", $_POST['web_apper_task_id'] ) );
		if ( $result ) :	
			return $this->sendResponse( 'Task deleted.', 'alert-success', 'Hurray!', true, $_POST['web_apper_task_id'] );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem deleting the Task. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Assigns a task to a user
     *
     */
	private function auto_assign() {
		if ( $_POST['assign_to_user'] == 'rotate_users' ) :
							
			$users = get_users( 'orderby=ID&order=ASC&role=' . $_POST['assign_to_role'] );
			$last_rotation = get_option( 'webapper_tasks_user_rotation', array() );
			foreach ( $users as $user ) :
				if ( $last_rotation[ $_POST['assign_to_role'] ] < $user->ID ) :
					$assign_to = $user->ID;
					$last_rotation[ $_POST['assign_to_role'] ] = $user->ID;
					break;
				endif;
			endforeach;
			if ( empty($last_rotation) || empty($assign_to) ) :
				$assign_to = $users[0]->ID;
				$last_rotation[ $_POST['assign_to_role'] ] = $users[0]->ID;
			endif;
			update_option( 'webapper_tasks_user_rotation', $last_rotation );
			return $assign_to;
			
		elseif ( $_POST['assign_to_user'] == 'least_to_do' ) :
		
			// least_to_do
			
		endif;
	}

}

$initialize = new RecordTasks(); 

?>